import 'dart:convert';
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import 'package:zhibao_flutter/api/commom/common_entity.dart';
import 'package:zhibao_flutter/api/commom/common_model.dart';
import 'package:zhibao_flutter/dialog/select_picture_dialog.dart';
import 'package:zhibao_flutter/util/http/http.dart';
import 'package:zhibao_flutter/widget/dialog/confirm_dialog.dart';
import 'package:zhibao_flutter/widget/dialog/update_dialog.dart';
import 'package:zhibao_flutter/zone.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart' as wxp;

CommonViewModel commonViewModel = CommonViewModel();

class Q1File {
  final File file;

  Q1File(this.file);
}

class CommonViewModel extends BaseViewModel {
  /*
  * 检查更新 [check update]
  *
  * */
  Future checkVersion(BuildContext context, [bool isToast = false]) async {
    if (kIsWeb) {
      return;
    }

    /// The ios also need show dialog for update but open link when click update.
    // if (Platform.isIOS) return;
    return checkUpdate(isToast ? context : null).then((rep) async {
      if (rep.data == null) {
        return;
      }
      VersionRspEntity model = rep.data;
      if (!strNoEmpty(model.version)) {
        myToast('checkVersionError'.tr);
        return;
      }
      if (Platform.isAndroid) {
        DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
        AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
        var sdkInt = androidInfo.version.sdkInt;
        var permissionOfInstallPackages =
            await Permission.requestInstallPackages.isGranted;
        var permissionOfStore = await Permission.storage.isGranted;
        var permissionOfExternalStore =
            await Permission.manageExternalStorage.isGranted;
        if ((sdkInt >= 23 && !permissionOfInstallPackages) ||
            !permissionOfStore ||
            (sdkInt >= 30 && !permissionOfExternalStore)) {
          await confirmDialog(context, text: "permissionInstallTip".tr,
              onPressed: () async {
            await Permission.requestInstallPackages.request().isGranted;
            await Permission.manageExternalStorage.request().isGranted;
            await Permission.storage.request().isGranted;
          });
        } else {
          await Permission.storage.request().isGranted;
        }
      }
      String versionStr = Q1DataRequest.versionStr;
      final int numberLocalVersion = int.parse(versionStr.replaceAll('.', ''));
      final int numberServerVersion =
          int.parse(model.version!.replaceAll('.', ""));
      final bool isNeedUpdate = numberLocalVersion < numberServerVersion;
      if (!isNeedUpdate) {
        var _tips = 'latestVersion'.tr;
        if (isToast) {
          myToast(_tips);
        } else {
          debugPrint(_tips);
        }
        return;
      }

      showDialog(
        context: context,
        builder: (ctx2) {
          return UpdateDialog(model, isForce: model.force ?? false);
        },
      );
    });
  }

  /*
  * CheckUpdateRequestModel
  *
  **/
  Future<ResponseModel> checkUpdate(BuildContext? context) async {
    // return ResponseModel.fromSuccess(
    //   VersionRspEntity(
    //     force: true,
    //     androidUrl: Platform.isAndroid
    //         ? 'https://oss.shenmeniuma.com/test_apk/cfa-2.5.12-foss-arm64-v8a-release%20%281%29.apk'
    //         : "https://apps.apple.com/cn/app/%E5%BE%AE%E4%BF%A1/id414478124",
    //     iosUrl: "",
    //     content: '是我的,,更新提示',
    //     version: '4.9.0',
    //   ),
    // );
    return CheckUpdateRequestModel()
        .sendApiAction(
      context,
      reqType: ReqType.get,
    )
        .then((rep) {
      print("CheckUpdateRequestModel::rep::${json.encode(rep)}");
      Q1Data.versionRspEntity = VersionRspEntity.fromJson(rep);
      return ResponseModel.fromSuccess(Q1Data.versionRspEntity);
    }).catchError((e) {
      return throwError(e);
    }).onError((error, stackTrace) {
      return onError(error, stackTrace);
    });
  }

  Future<List<Q1File>> pickFile(
    BuildContext context,
    ImageSource source,
    int maxCount, {
    bool isVideo = false,
  }) async {
    List<Q1File> pickResultFile = [];
    if (source == ImageSource.gallery) {
      try {
        wxp.RequestType requestType =
            isVideo ? wxp.RequestType.video : wxp.RequestType.image;
        LogUtil.d("requestType::${requestType.toString()}");
        LogUtil.d("maxCount::${maxCount.toString()}");
        List<wxp.AssetEntity>? resultList = await wxp.AssetPicker.pickAssets(
          context,
          pickerConfig: wxp.AssetPickerConfig(
            maxAssets: maxCount,
            pageSize: 320,
            gridCount: 4,
            themeColor: MyTheme.themeColor(),
            filterOptions: FilterOptionGroup(containsLivePhotos: !isVideo),
            requestType: requestType,

            /// For support localization we must cancel it.
            // textDelegate: wxp.AssetPickerTextDelegate(),
          ),
        );
        if (listNoEmpty(resultList)) {
          for (wxp.AssetEntity assetEntity in resultList!) {
            pickResultFile.add(Q1File((await assetEntity.file)!));
            LogUtil.d(
                "CommonViewModel：pickFile：序列文件:${(await assetEntity.file)?.path}}");
          }
        }
      } catch (e) {
        mySuccessToast('permissionComplete'.tr);
        LogUtil.d("出现错误::${e.toString()}");
      }
    } else {
      String? cameraPath;
      bool isReadDisposeOfCamera = false;
      final cameraLocate = cameraPickerTextDelegates.firstWhere(
          (element) => element.languageCode == AppConfig.locale.languageCode,
          orElse: () {
        return EnglishCameraPickerTextDelegate();
      });

      if (isVideo) {
        final AssetEntity? entity = await CameraPicker.pickFromCamera(
          context,
          pickerConfig: CameraPickerConfig(
            enableRecording: true,
            onlyEnableRecording: true,
            resolutionPreset: ResolutionPreset.medium,
            theme: MyTheme.themeForPlugin(),
            textDelegate: cameraLocate,
          ),
        );
        cameraPath = (await entity?.file)?.path;
      } else {
        LogUtil.d("resolutionPreset: ResolutionPreset.high,::");
        final AssetEntity? entity = await CameraPicker.pickFromCamera(
          context,
          pickerConfig: CameraPickerConfig(
            enableRecording: false,
            resolutionPreset: ResolutionPreset.medium,
            theme: MyTheme.themeForPlugin(),
            textDelegate: cameraLocate,
          ),
        );

        /// Compress video function.
        // String? cameraFirstPath = (await entity?.file)?.path;
        // if (cameraFirstPath == null) return [];
        //
        // MediaInfo? mediaInfo = await VideoCompress.compressVideo(
        //   cameraFirstPath,
        //   quality: VideoQuality.MediumQuality,
        //   deleteOrigin: true, // It's false by default
        // );
        // LogUtil.d("compress video after ${mediaInfo?.path}");
        // if (mediaInfo == null) return [];
        // cameraPath = mediaInfo.path;

        cameraPath = (await entity?.file)?.path;
      }

      if (strNoEmpty(cameraPath)) {
        pickResultFile = [Q1File(File(cameraPath!))];
      }
    }
    return pickResultFile;
  }

  /*
  * CityListRequestModel
  *
  **/
  Future<ResponseModel> cityList(BuildContext? context) async {
    return CityListRequestModel()
        .sendApiAction(
      context,
      reqType: ReqType.post,
    )
        .then((rep) {
      return ResponseModel.fromSuccess(rep);
    }).catchError((e) {
      return throwError(e);
    }).onError((error, stackTrace) {
      return onError(error, stackTrace);
    });
  }

  /*
  * UploadAvatarRequestModel
  *
  **/
  Future<ResponseModel> uploadAvatar(
    BuildContext context, {
    required final File file,
    ProgressCallback? onSendProgress,
  }) async {
    return UploadAvatarRequestModel(file)
        .sendApiAction(context,
            reqType: ReqType.file, onSendProgress: onSendProgress)
        .then((rep) {
      return ResponseModel.fromSuccess(rep ?? true);
    }).catchError((e) {
      return throwError(e);
    }).onError((error, stackTrace) {
      return onError(error, stackTrace);
    });
  }
}
